import 'dart:math';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:xm_app/common/http/api_response.dart';
import 'package:xm_app/common/logger/LoggerUtil.dart';
import 'package:xm_app/common/ui/AppTheme.dart';
import 'package:xm_app/dao/FundDao.dart';
import 'package:xm_app/dao/VodDao.dart';
import 'package:xm_app/model/FundMNFInfo.dart';

import 'FundPage.dart';

class FundController extends GetxController {
  static const String CACHE_KEY = "FUND_CACHE";
  final inputController = new TextEditingController();
  EasyRefreshController easyRefreshController = EasyRefreshController();
  FocusNode focusNode = FocusNode();
  FundMNFInfo fundMNFInfo = FundMNFInfo();
  MNFItem sh000001;
  final listKey = GlobalKey<SliverAnimatedListState>();

  void onInit() {
    super.onInit();
    print("SearchController onInit");
    inputController.addListener(() {
      if (inputController.value.text != "") {
        update();
      }
    });
    getSH000001();
    getData();
  }

  getRefresh() async {
    await getSH000001();
    await getData();
    easyRefreshController.finishRefresh(success: true);
  }

  getData() async {
    List codes = SpUtil.getStringList(CACHE_KEY, defValue: List());
    if (codes.length == 0) {
      fundMNFInfo = FundMNFInfo();
      logDebug("codes.length == 0");
      update();
      return;
    }
    ApiResponse<FundMNFInfo> res = await FundDao().getFundMNFInfo(codes.join(","));
    if (res.status == Status.ERROR) {
      SmartDialog.showToast(res.exception.message);
      return;
    }
    res.data.datas.sort((left, right) => double.parse(right.gSZZL).compareTo(double.parse(left.gSZZL)));
    fundMNFInfo = res.data;
    update();
  }

  getSH000001() async {
    final nNFItem = await FundDao().getSH000001();
    sh000001 = nNFItem;
    update();
  }

  addFundBtn() async {
    String code = inputController.text;
    if (inputController.text.length == 0) {
      SmartDialog.showToast("请输入要添加的代码", alignment: Alignment.center);
      return;
    }
    List<String> codes = SpUtil.getStringList(CACHE_KEY, defValue: List<String>());
    if (codes.contains(code)) {
      SmartDialog.showToast("已经添加该代码", alignment: Alignment.center);
      return;
    }

    ApiResponse<FundMNFInfo> res = await FundDao().getFundMNFInfo(code);
    if (res.status == Status.ERROR) {
      SmartDialog.showToast(res.exception.message);
      return;
    }
    if (res.data.totalCount == 0) {
      logDebug("错误代码");
      SmartDialog.showToast("错误代码", alignment: Alignment.center);
      return;
    }

    codes.add(code);
    final set = Set<String>();
    set.addAll(codes);
    codes = set.toList();
    await SpUtil.putStringList(CACHE_KEY, codes);
    inputController.text = "";
    focusNode.unfocus();
    getData();
  }

  delCaChe(MNFItem item) async {
    List<String> codes = SpUtil.getStringList(CACHE_KEY, defValue: List<String>());
    codes.removeWhere((String element) => element == item.fCODE);
    await SpUtil.putStringList(CACHE_KEY, codes);
  }

  cleanText() {
    inputController.text = "";
    update();
  }

  delItemBtn(MNFItem item) {
    Get.defaultDialog(
        title: "确定删除",
        confirm: FlatButton(
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          onPressed: () async {
            await delCaChe(item);
            Get.back(closeOverlays: true);
            await getData();
          },
          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
          child: Text(
            "删除",
            style: TextStyle(color: AppTheme.pinkColor),
          ),
          shape:
              RoundedRectangleBorder(side: BorderSide(color: AppTheme.pinkColor, width: 2, style: BorderStyle.solid), borderRadius: BorderRadius.circular(100)),
        ),
        cancel: FlatButton(
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          onPressed: () {
            Get.back(closeOverlays: true);
          },
          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
          child: Text(
            "取消",
            style: TextStyle(color: AppTheme.pinkColor),
          ),
          shape:
              RoundedRectangleBorder(side: BorderSide(color: AppTheme.pinkColor, width: 2, style: BorderStyle.solid), borderRadius: BorderRadius.circular(100)),
        ),
        middleText: "确定删除 ${item.sHORTNAME} 吗？");
  }
// controller.listKey.currentState.insertItem(0);
// controller.listKey.currentState.removeItem(0, (context, animation) => _buildItem(controller.fundMNFInfo.datas[0], animation));
}
